//
//  CAKeyframeAnimation_TenNineEight_VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/8/18.
//

import UIKit

class CAKeyframeAnimation_TenNineEight_VC: UIViewController {

    private var countDownNumberLabel: UILabel!
    private var totalCount: Int = 10
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        countDownNumberLabel = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        view.addSubview(countDownNumberLabel)
        countDownNumberLabel.font = .boldSystemFont(ofSize: 30)
        countDownNumberLabel.textColor = .black
        countDownNumberLabel.textAlignment = .center
        countDownNumberLabel.center = view.center
        countDownNumberLabel.text = "10"
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        countDownNumberLabel.text = "10"
        totalCount = 10
        startAnimation()
        startTimer()
    }
    
    private func startAnimation() {
        let keyFrameAnimation = CAKeyframeAnimation.init(keyPath: CALayer.KeyPath.transform_scale)
        /// 字体变化大小
        let value1 = NSNumber.init(value: 1.0)
        let value2 = NSNumber.init(value: 1.73)
        let value3 = NSNumber.init(value: 1.0)
        keyFrameAnimation.values = [value1, value2, value3]
        
        let time1 = NSNumber.init(value: 0.0)
        let time2 = NSNumber.init(value: 0.25)
        let time3 = NSNumber.init(value: 1.0)
        keyFrameAnimation.keyTimes = [time1, time2, time3]
        
        keyFrameAnimation.duration = 1;
        countDownNumberLabel.layer.add(keyFrameAnimation, forKey: "countDown_label_scale_key")
    }
    
    private func startTimer() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
        }
    }
    
    @objc private func countDown() {
        if totalCount > 0 {
            totalCount -= 1
            countDownNumberLabel.text = "\(totalCount)"
            startAnimation()
        } else {
            countDownNumberLabel.text = "0"
            timer?.invalidate()
            timer = nil
        }
    }

}
